<?php

namespace ltcms\response;

/**
 * Jsonp Response
 */
class Jsonp extends Response
{
    // 输出参数
    protected $options = [
        'var_jsonp_handler'     => 'callback',
        'default_jsonp_handler' => 'jsonpReturn',
        'json_encode_param'     => JSON_UNESCAPED_UNICODE,
    ];

    protected $contentType = 'application/javascript';

    public function __construct($data = '', int $code = 200)
    {
        $this->init($data, $code);
    }

    /**
     * 处理数据
     * @param mixed $data
     * @param $templatePath
     * @access protected
     * @return string
     * @throws \Exception
     */
    protected function output($data, $templatePath)
    {
        try {
            $varJsonpHandler = request()->param($this->options['var_jsonp_handler'], "");
            $handler         = !empty($varJsonpHandler) ? $varJsonpHandler : $this->options['default_jsonp_handler'];

            $data = json_encode($data, $this->options['json_encode_param']);

            if (false === $data) {
                throw new \InvalidArgumentException(json_last_error_msg());
            }

            $data = $handler . '(' . $data . ');';

            return $data;
        } catch (\Exception $e) {
            if ($e->getPrevious()) {
                throw $e->getPrevious();
            }
            throw $e;
        }
    }
}
